#!/usr/bin/env python
import os
import sys
import re
import db
from db import *
from output import *
from info import *
from os.path import join as joinpath

class DbStat(object):
    def __init__(self, source, bench, stat, conf, **kwargs):

        self.statData = None

        stat = stat.replace('system', 'system0')

        db_stat = source.getStat(stat)

        if len(db_stat) == 0:
            raise AttributeError, 'No such statistic for %s' % \
                  stat

        run_name = bench + '-' + conf

        for i,db_s in enumerate(db_stat):

            if db_s.name != stat:
                print "Warning: stats are ignored: %s" % db_s.name
                continue

            dist_data = None

            if db_s.type == 'DIST' or db_s.type == 'VECTORDIST':

                dist_data = source.data(db_s)

                db_run = source.allRunNames[run_name]

                if not dist_data.__contains__(db_run.run):
                    raise AttributeError, 'No such statistic %s for %s' % \
                          (conf, bench)

                vec_size = len(dist_data[db_run.run][0])

                for k in range(vec_size):
                    data_vector = []

                    for d in dist_data[db_run.run][0:db_s.size]:
                        data_vector.append(d[k])

                    full_dist = FullDist(dist_data[db_run.run][-1][k],
                                         dist_data[db_run.run][-2][k],
                                         dist_data[db_run.run][-3][k],
                                         dist_data[db_run.run][-4][k],
                                         dist_data[db_run.run][-5][k],
                                         dist_data[db_run.run][-6][k],
                                         data_vector,
                                         dist_data[db_run.run][-7][k],
                                         db_s.min, db_s.max, db_s.bktsize,
                                         db_s.size)

                    self.statData = full_dist

#                    full_dist.display(db_s.name, db_s.desc,
#                                      db_s.flags, db_s.precision)

            else:
                v = source.get(run_name, db_s)

                if v == None:
                    raise AttributeError, 'No such statistic %s for %s' % \
                          (conf, bench)

                self.statData = v 

    def data(self):
        return self.statData

    def pdf(self):

        if not isinstance(self.statData, FullDist):
            raise AttributeError, "Not a dist"

        return self.statData.pdf()

    def cdf(self):

        if not isinstance(self.statData, FullDist):
            raise AttributeError, "Not a dist"

        return self.statData.cdf()


